package imagecutter;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

/**
 *
 * @author faila
 */
public class Cutter {

    Configuration conf = new Configuration();
    ImageOperation image = new ImageOperation();
    int cols, rows, sizeHeight, sizeWidth, countSaveImages;

    /**
     * Load and set parametres of image
     *@param String path, String configFile
     */
    public Cutter(String configFile, String path) {
        image.loadImageFile(path);
        image.loadImageProperties();
        conf.loadPropertiesFile(configFile);

        sizeHeight = conf.getPropertyAsInteger(Configuration.HEIGHT);
        sizeWidth = conf.getPropertyAsInteger(Configuration.WIDTH);

        /*
        if cols (rows) is a float number, a number is round up.
         */
        cols = (int) Math.ceil((double) image.imageHeight / (double) sizeHeight);
        rows = (int) Math.ceil((double) image.imageWidht / (double) sizeWidth);

        countSaveImages = conf.getPropertyAsInteger(Configuration.COUNT_SAVED_IMAGES);

    }

    /**
    Cut image from input file "*.jpg" onto some parts of small images
     */
    public void cutImage() {
        int countImage = 0;
        boolean endOfImage = false;
        BufferedImage[] arrayResultImages = new BufferedImage[countSaveImages];

        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                if (countImage != countSaveImages) {
                    arrayResultImages[countImage] = new BufferedImage(sizeWidth, sizeHeight, image.getImageType());
                    Graphics2D graphicImage = arrayResultImages[countImage++].createGraphics();
                    graphicImage.drawImage(image.img, 0, 0, sizeWidth, sizeHeight, sizeWidth * j, sizeHeight * i, (int) (sizeWidth * j + sizeWidth), (int) (sizeHeight * i + sizeHeight), null);
                    graphicImage.dispose();

                } else {
                    endOfImage = true;
                    break;
                }
            }
            if (endOfImage) {
                break;
            }
        }
        image.createImage(arrayResultImages);
    }
}
